import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'

Vue.use(Router)

const router =  new Router({
  routes: [
    {
      path:'/',
      redirect:'/login'      //重定向
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/home',
      component: Home,
      redirect:'/welcome',
      children:[
        {
          path:'/welcome',
          component:()=>import('../view/user/Welcome.vue')
        },
        {
          path:'/users',
          component:()=>import('../view/user/Users.vue')
        },
        {
          path:'/rights',
          component:()=>import('../view/power/Rights.vue')
        },
        {
          path:'/roles',
          component:()=>import('../view/power/Roles.vue')
        },
        {
          path:'/categories',
          component:()=>import('../view/goods/Cate.vue')
        },
        {
          path:'/params',
          component:()=>import('../view/goods/Params.vue')
        },
        {
          path:'/goods',
          component:()=>import('../view/goods/List.vue')
        },
        {
          path:'/goods/add',
          component:()=>import('../view/goods/Add.vue')
        },
        {
          path:'/orders',
          component:()=>import('../view/order/Order.vue')
        },
        {
          path:'/reports',
          component:()=>import('../view/report/Report.vue')
        }
      ]
    }
  ]
})

//挂载路由导航守卫
router.beforeEach((to,from,next)=>{
  //to将要访问的路径
  //from代表从哪个路径跳转而来
  //next是一个函数，代表放行【next()放行，next('/login')强制跳转】

  //如果用户访问的登录页，直接放行
  if(to.path==='/login') return next();
  //从sessionStora中获取到保存的token值
  const tokenStr = window.sessionStorage.getItem('token')
  //没有token，强制跳转到登录页
  if(!tokenStr) return next('./login')
  next()
})

export default router